//
//  TransitionToListVC.m
//  Btpin
//
//  Created by Vic on 2019/12/14.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "TransitionToListVC.h"
#import "JobCollectionViewCell.h"
#import "JobCell.h"
#import "PersonalHomeViewController.h"
#import "JobDetailViewController.h"

@implementation TransitionToListVC

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    JobDetailViewController *fromVC = (JobDetailViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    PersonalHomeViewController *toVC = (PersonalHomeViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *containerView = [transitionContext containerView];
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    
//    JobCollectionViewCell *toControllerImageCell = (JobCollectionViewCell *)[fromVC.jobTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    JobCell *toControllerImageCell = (JobCell *)[fromVC.jobTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UIView *cellImageSnapshot = [toControllerImageCell.bgView snapshotViewAfterScreenUpdates:NO];
    cellImageSnapshot.frame = [containerView convertRect:toControllerImageCell.bgView.frame fromView:toControllerImageCell.bgView.superview];
    toControllerImageCell.bgView.hidden = YES;
    
    JobCollectionViewCell *cell = (JobCollectionViewCell *)[toVC.cCollectionView cellForItemAtIndexPath:toVC.selectedIndexPath];
    cell.bgView.hidden = YES;
    
    toVC.view.frame = [transitionContext finalFrameForViewController:toVC];
    [containerView insertSubview:toVC.view belowSubview:fromVC.view];
    [containerView addSubview:cellImageSnapshot];
    
    [UIView animateWithDuration:duration animations:^{
        fromVC.view.alpha = 0.0;
        toVC.cCollectionView.alpha = 1.0;
        cellImageSnapshot.frame = [containerView convertRect:cell.bgView.frame fromView:cell.bgView.superview];
    } completion:^(BOOL finished) {
        [cellImageSnapshot removeFromSuperview];
        toControllerImageCell.bgView.hidden = NO;
        cell.bgView.hidden = NO;
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
    }];
}
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.35;
}

@end
